<template>
	<view class="root safe-area-inset-bottom pt-44 f1 jc-center">
		<view class="ai-center">
			<image
				:style="{ width: `64%`, height: `90rpx` }"
				src="/static/img/pic-hello.png"
				mode="aspectFill"
			/>
			<text class="fs-40 color-333 fw-700 mt-48">欢迎注册运输APP</text>
		</view>
		<view class="mt-100">
			<block v-for="(item, key) in model" :key="key">
				<picker
					v-if="item.type === `picker`"
					:range="item.range"
					:mode="item.mode"
					:range-key="item.rangeKey"
					@change="changePicker($event, key)"
					@columnchange="columnChangePicker($event, key)"
				>
					<view
						:style="{
							boxShadow: `0 8rpx 44rpx 0 rgba(207, 207, 207, 0.3)`,
							minHeight: `96rpx`,
							margin: `22rpx 56rpx`,
							padding: `20rpx`,
						}"
						class="br-20 fd-row ai-center"
					>
						<image
							class="width-32 height-38 mr-18"
							:src="`/static/img/icon-${key}.png`"
							mode="aspectFill"
						/>
						<input
							type="text"
							:placeholder="item.placeholder"
							:disabled="true"
							class="f1 fs-30"
							placeholder-class="color-ccc fs-28"
							:value="item.value"
						/>

						<uni-icons type="arrowdown" color="#4052e4" />
					</view>
				</picker>

				<view
					v-else
					:style="{
						boxShadow: `0 8rpx 44rpx 0 rgba(207, 207, 207, 0.3)`,
						minHeight: `96rpx`,
						margin: `22rpx 56rpx`,
						padding: `20rpx`,
					}"
					class="br-20 fd-row ai-center"
				>
					<image
						class="width-32 height-38 mr-18"
						:src="`/static/img/icon-${key}.png`"
						mode="aspectFill"
					/>
					<input
						:type="item.type"
						:maxlength="item.maxlength"
						:placeholder="item.placeholder"
						:value="item.value"
						class="f1 input fs-30"
						placeholder-class="color-ccc fs-28"
						@input="inputValue($event, key)"
					/>

					<button
						v-if="key === `captcha`"
						class="fs-28 color-4052e4 border-none lh-2"
						:plain="true"
						hover-class="tap-hover"
						:disabled="captchaBtn.disabled"
						@click="getCaptcha"
					>
						{{ captchaBtn.text }}
					</button>
				</view>
			</block>
		</view>

		<button
			:style="{
				backgroundImage: `linear-gradient(45deg, #4051E3, #4672FF)`,
				margin: `134rpx 55rpx 0`,
			}"
			class="color-fff fs-32 br-20 lh-3 fw-700"
			hover-class="tap-hover"
			@click="submit"
		>
			注册
		</button>

		<view class="ai-center mt-40">
			<view class="mt-30 fd-row jc-center ai-center fs-22">
				<label>
					<switch @change="isChecked" type="checkbox" :checked="isAgree" color="#fff" />
					<text class="color-999">我已阅读并同意</text>
				</label>

				<navigator
					class="color-1b1b1b"
					hover-class="tap-hover"
					hover-start-time="50"
					:url="'privacy' | webviewURL($config)"
				>
					《隐私政策》
				</navigator>
				<text class="color-999">和</text>
				<navigator
					class="color-1b1b1b"
					hover-class="tap-hover"
					:url="'protocol' | webviewURL($config)"
				>
					《用户使用协议》
				</navigator>
			</view>
		</view>
	</view>
</template>

<script lang="ts">
	import { Vue, Component } from "vue-property-decorator";
	import { isPhoneNumber, sleep, Storage, combineURLs, transformURL } from "@/static/libs/utils";

	@Component({
		filters: {
			webviewURL(type: string, { currentEnv, path }: AnyObject): string {
				/**
				 *  fetch(location.origin + location.hash.slice(1) + location.search)
				 *	  .then(res => res.json())
				 *	  .then(res => document.write(res.data.content));
				 */
				return (
					"/pages/common/webview?url=" +
					transformURL(
						combineURLs(currentEnv.http, path.richText),
						{ token: Storage.get("authorization") },
						path.api + "/" + type
					)
				);
			},
		},
	})
	export default class ResetPassword extends Vue {
		// component property
		isAgree: boolean = false;
		baseData: AnyObject = {};
		captchaBtn: AnyObject = {
			text: "获取验证码",
			disabled: false,
			count: 60,
		};
		timer: null | number = null;
		model: AnyObject = {
			account: {
				type: "number",
				maxlength: 11,
				placeholder: "请输入手机号码",
				value: "",
				data: "",
				name: "mobile",
			},
			captcha: {
				type: "number",
				maxlength: 6,
				placeholder: "请输入验证码",
				value: "",
				data: "",
				name: "code",
			},
			password: {
				type: "password",
				maxlength: 16,
				placeholder: "请输入密码",
				value: "",
				data: "",
				name: "password",
			},
			identity: {
				type: "picker",
				placeholder: "请选择身份",
				range: [
					{ id: 1, text: "用户" },
					{ id: 2, text: "司机" },
					{ id: 4, text: "员工" },
				],
				mode: "selector",
				rangeKey: "text",
				value: "",
				data: "",
				name: "identity",
			},
		};
		procedureRange: AnyObject = [];
		companyRange: AnyObject = [];

		onLoad() {
			this.$request.get("/changList").then(({ data }) => (this.procedureRange = data));
			this.$request.get("/companyList").then(({ data }) => (this.companyRange = data));
		}

		async changePicker({ detail }: AnyObject, key: string) {
			const { $set, model, procedureRange, companyRange } = this;
			const option = model[key];

			switch (option.mode) {
				case "selector":
					option.value = option.range[detail.value][option.rangeKey];
					option.data = option.range[detail.value].id;

					if (key !== "identity") return;

					if (+option.range[detail.value].id === 4) {
						const { chang, gongxu } = procedureRange;

						$set(model, "procedure", {
							type: "picker",
							placeholder: "请选择工序",
							range: [chang, gongxu[chang[0].id]],
							mode: "multiSelector",
							rangeKey: "name",
							value: "",
							data: "",
							name: "gongxu",
						});
					} else {
						model.procedure && delete model.procedure;
					}

					if (+option.range[detail.value].id === 1) {
						$set(model, "company", {
							type: "picker",
							placeholder: "请选择公司",
							range: companyRange,
							mode: "selector",
							rangeKey: "name",
							value: "",
							data: "",
							name: "company",
						});
						uni.hideLoading();
					} else {
						model.company && delete model.company;
					}

					break;
				case "multiSelector":
					const result = option.range.map(
						(item: AnyObject, index: number) => item[detail.value[index]]
					);

					option.value = result.map((item: AnyObject) => item[option.rangeKey]).join(" - ");
					option.data = result.map((item: AnyObject) => item.id).toString();
				default:
					break;
			}
		}

		columnChangePicker({ detail }: AnyObject, key: string) {
			const { $set, model } = this;

			switch (key) {
				case "procedure":
					const { gongxu, chang } = this.procedureRange;
					!+detail.column && $set(model[key].range, 1, gongxu[chang[detail.value].id]);
					break;
				default:
					break;
			}
		}

		inputValue(e: AnyObject, key: string) {
			const option = this.model[key];
			option.value = option.data = e.detail.value;
		}

		isChecked({ detail }: AnyObject) {
			this.isAgree = detail.value;
		}

		countdown() {
			this.captchaBtn.disabled = true;
			this.timer = setInterval(() => {
				this.captchaBtn.count--;
				this.captchaBtn.text = `${this.captchaBtn.count}s后再试`;

				if (this.captchaBtn.count <= 0) {
					this.captchaBtn.disabled = false;
					this.captchaBtn.text = "获取验证码";
					this.captchaBtn.count = 60;
					this.timer && clearInterval(this.timer);
					this.timer = null;
				}
			}, 1000);
		}

		getCaptcha() {
			if (this.captchaBtn.disabled) return;

			isPhoneNumber(this.model.account.data)
				? this.$request
						.get("/sendSms", {
							mobile: this.model.account.data,
						})
						.then(({ msg: title }) =>
							uni.showToast({
								title,
								success: this.countdown,
							})
						)
				: uni.showToast({
						title: "请检查手机号码是否输入正确",
						icon: "none",
				  });
		}

		async submit() {
			if (!this.isAgree) {
				uni.showToast({
					icon: "none",
					title: "你需要先同意相关协议和政策后才能继续",
				});
				return;
			}

			const params: AnyObject = {},
				verify = Object.values(this.model).every((item) => {
					params[item.name] = item.data;

					!item.data && uni.showToast({ title: item.placeholder, icon: "none" });

					return Boolean(item.data);
				});

			if (!verify) return;

			uni.showLoading({ title: "Loading..." });
			const { msg: title } = await this.$request.post("/register", params);

			uni.showToast({ title, duration: 1000, mask: true });
			await sleep(1);
			uni.navigateBack({});
		}
	}
</script>

<style lang="scss" scoped>
	// scss
	::v-deep {
		switch {
			transform: scale(0.6);
			.wx-checkbox-input,
			.uni-checkbox-input {
				border-color: #0d81f6;
				background-color: transparent;
			}

			.wx-checkbox-input.wx-checkbox-input-checked,
			.uni-checkbox-input.uni-checkbox-input-checked {
				background-color: #0d81f6;
			}

			&:not([disabled]) {
				.wx-checkbox-input:hover,
				.uni-checkbox-input:hover {
					border-color: #0d81f6;
				}
			}
		}
	}
</style>